package com.github.jspxnet.worktask.core.node;

import com.github.jspxnet.utils.BeanUtil;
import com.github.jspxnet.worktask.model.dto.ConfFlowNodeDto;
import com.github.jspxnet.worktask.model.dto.ProcessResponse;
import com.github.jspxnet.worktask.model.enums.FlowNodeEnumType;
import com.github.jspxnet.worktask.table.ConfFlowNode;
import com.github.jspxnet.worktask.table.WorkTask;
import com.github.jspxnet.worktask.util.WorkFlowUtil;
import java.util.List;


/**
 * 合并分支节点
 * 1.得到当前所有已经完成的任务节点
 */
public class JoinNodeAction extends BaseNodeAction {
    @Override
    public ProcessResponse<?> execute() {

        if (currentConfFlowNode.getFlowNodeType() != FlowNodeEnumType.GATEWAY.getValue())
        {
            return ProcessResponse.error("网关节点配置有错误:" + currentConfFlowNode.getNodeId());
        }

        try {
            List<ConfFlowNode>  joinList = confWorkFlowDAO.getJoinConfFlowNode(currentWorkTask.getFlowNo(),currentWorkTask.getNamespace(),currentConfFlowNode.getNodeId());
            List<String> joinNodeList = BeanUtil.copyFieldList(joinList,"nodeId");
            List<WorkTask> taskJoinNodeList = runtimeServiceDAO.getJoinExeNodeList(currentWorkTask.getFlowNo(),currentWorkTask.getNamespace(),currentWorkTask.getDocumentNo(),joinNodeList);
            List<String> taskNodeList = BeanUtil.copyFieldList(taskJoinNodeList,"nodeId");
            if (joinList.size()!=taskNodeList.size() && runtimeServiceDAO.updateJoinFinished(currentWorkTask.getFlowNo(),currentWorkTask.getNamespace(),currentConfFlowNode.getNodeId(),currentWorkTask.getDocumentNo())>=0)
            {
                 inNextNode();
            }
            else
            {
                List<String> noExeNodeList = WorkFlowUtil.getNotExeNodeList(joinNodeList,taskNodeList);
                ConfFlowNode noExeConfFlowNode = confWorkFlowDAO.getConfFlowNode(currentConfFlowNode.getFlowNo(),currentConfFlowNode.getNamespace(),noExeNodeList.get(0));
                ProcessResponse<?> processResponse = ProcessResponse.error("等待分支节点合并:"+ noExeConfFlowNode.getTitle() + "[" + noExeConfFlowNode.getNodeId()+ "]");
                processResponse.setFlowNode(BeanUtil.copy(noExeConfFlowNode, ConfFlowNodeDto.class));
                return processResponse;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ProcessResponse.error(e.getMessage());
        }
        return ProcessResponse.success(currentWorkTask);
    }

}
